package com.shensi.adminCollect.service.station.impl;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.shensi.adminCollect.common.utils.http.HttpUtils;
import com.shensi.common.core.constant.RedisKeyPrefixConstant;
import com.shensi.common.core.domain.AjaxResult;
import com.shensi.common.core.exception.CustomException;
import com.shensi.common.core.utils.StringUtils;
import com.shensi.adminCollect.domain.station.Enterprise;
import com.shensi.adminCollect.domain.station.MemberCardInfo;
import com.shensi.adminCollect.domain.station.WxMenu;
import com.shensi.adminCollect.enums.station.WxColorEnum;
import com.shensi.adminCollect.mapper.station.WxMenuMapper;
import com.shensi.adminCollect.service.station.GzhMenuService;
import com.shensi.adminCollect.service.station.IEnterpriseService;
import com.shensi.adminCollect.service.station.IThirdPartyWeChatService;
import com.shensi.adminCollect.domain.system.Token;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;
@RefreshScope
@Service
@Slf4j
public class GzhMenuServiceImpl implements GzhMenuService {
    //创建自定义公众号菜单
    private static final String CREATE_MENU_PERMISSION_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
    //获取token
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APP_SECRET";
    //获取公众号菜单
    private static final String GET_MENU_PERMISSION_URL = "https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info?access_token=ACCESS_TOKEN";
    //
    private static final String GET_GZH_AUTHORIZER_INFO_URL = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=ACCESS_TOKEN";
    private static final String API_QUERY_AUTH = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=ACCESS_TOKEN";
    private static final String CARD_LIST_URL = "https://api.weixin.qq.com/card/list?access_token=ACCESS_TOKEN";
    private static final String BATCH_GET_URL = "https://api.weixin.qq.com/card/batchget?access_token=ACCESS_TOKEN";
    //获取会员卡信息
    private static final String CARD_GET_URL = "https://api.weixin.qq.com/card/get?access_token=ACCESS_TOKEN";
    //修改会员卡
    private static final String CARD_UPDATE_URL = "https://api.weixin.qq.com/card/update?access_token=ACCESS_TOKEN";
    private static final String GET_MEDIA_URL = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=";
    private static final String WXAMP_LINK_GET = "https://api.weixin.qq.com/cgi-bin/wxopen/wxamplinkget?access_token=ACCESS_TOKEN";
    private static final String MEDIA_UPLOAD_URL = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=image";
    private static final String GET_MATERIAL_URL = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=ACCESS_TOKEN&type=image";
    private static final String GET_USER_INFO_URL = "https://api.weixin.qq.com/card/membercard/userinfo/get?access_token=TOKEN";

    @Value("${wechat.thirdParty.appid}")
    private  String componentAppId ;
    @Value("${wechat.thirdParty.secrect}")
    private   String componentAppSecret ;


    @Resource
    private IEnterpriseService enterpriseService;


    @Resource
    private IThirdPartyWeChatService thirdPartyWeChatService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private WxMenuMapper wxMenuMapper;



    @Override
    public AjaxResult updateGzhMenu(Long enterpirseId, JSONObject jsonObject) throws Exception {
        Enterprise enterprise = enterpriseService.selectEnterpriseById(enterpirseId);
        String gzhAppId = enterprise.getGzhAppId();
        String gzhAppSecret = enterprise.getGzhAppSecret();
//        || StringUtils.isBlank(gzhAppSecret) 去除不必要的参数
        if (StringUtils.isBlank(gzhAppId)) {
            throw new CustomException("请配置appId和appSecret");
        }

        //获取token
        String accessToken = getAccessToken(gzhAppId, gzhAppSecret);
        if (StringUtils.isEmpty(accessToken)) {
            throw new CustomException("获取access_token失败!");
        }

        //获取当前菜单
        JSONObject menuPermission = getMenuPermission(accessToken);
        log.info("当前菜单权限【{}】", menuPermission);
        // 设置事件
        //前端传过来的结构不一致，去掉数据里的"list"
        String transformJson = transformJson(jsonObject.toString());
        //设置事件   前端那边不好处理  按钮的key其实是对应的值，后端生成一个key存进数据库wx_menu表，
        // 查询的调微信接口查询的时候查出来的key，再去查具体的值返回给前端，事件推送的时候也是根据表里的key去查具体的值
        JSONObject jsonRes = setClickEvent(JSONObject.parseObject(transformJson));
        //设置菜单
        boolean success = setMenuPermission(accessToken, jsonRes);
        if (!success) {
            return AjaxResult.error("公众号菜单设置失败");
        }

        return AjaxResult.success("公众号菜单设置成功");
    }

    public JsonNode replaceClickKey(JsonNode jsonNode) {
        if (jsonNode.isObject()) {
            JsonNode typeNode = jsonNode.get("type");
            if (typeNode != null && typeNode.isTextual() && typeNode.asText().equals("click")) {
                JsonNode keyNode = jsonNode.get("key");

                if (keyNode != null && keyNode.isTextual()) {
                    String uuid = UUID.randomUUID().toString();
                    ((ObjectNode) jsonNode).put("key", uuid);
                    WxMenu wxMenu = new WxMenu();
                    wxMenu.setMenuKey(uuid);
                    wxMenu.setValue(keyNode.asText());
                   //插入数据库
                    wxMenuMapper.insertWxMenu(wxMenu);
                }
            }
            jsonNode.fields().forEachRemaining(entry -> replaceClickKey(entry.getValue()));
        } else if (jsonNode.isArray()) {
            jsonNode.forEach(this::replaceClickKey);
        }
        return jsonNode;
    }


    private JSONObject setClickEvent(JSONObject jsonObject){
        //设置事件
        //替换调原本的
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = null;
        try {
            rootNode = mapper.readTree(jsonObject.toString());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        JsonNode jsonNode = replaceClickKey(rootNode);

        String stringJsonNode = jsonNode.toString();
        JSONObject jsonObjectRes = JSONObject.parseObject(stringJsonNode);
        return jsonObjectRes;

    }

    public static List<WxMenu> extractMenus(String json) {
        List<WxMenu> menus = new ArrayList<>();

        JSONObject jsonObject = JSONObject.parseObject(json);
        JSONArray buttonArray = jsonObject.getJSONArray("button");

        for (int i = 0; i < buttonArray.size(); i++) {
            JSONObject button = buttonArray.getJSONObject(i);
            String name = button.getString("name");
            String type = button.getString("type");
            String key = button.getString("key");

            WxMenu menu = new WxMenu();
            menu.setMenuKey(name);
            menu.setValue(type);
            menus.add(menu);

            JSONArray subButtonArray = button.getJSONArray("sub_button");
            if (subButtonArray != null) {
                for (int j = 0; j < subButtonArray.size(); j++) {
                    JSONObject subButton = subButtonArray.getJSONObject(j);
                    String subButtonName = subButton.getString("name");
                    String subButtonType = subButton.getString("type");
                    String subButtonKey = subButton.getString("key");

                    WxMenu subMenu = new WxMenu();
                    menu.setMenuKey(subButtonKey);
                    menu.setValue(subButtonKey);
                    menus.add(subMenu);
                }
            }
        }

        return menus;
    }


    // 设置菜单权限
    private static boolean setMenuPermission(String accessToken, JSONObject permission) {

        try {
            OkHttpClient client = new OkHttpClient();
            String url = CREATE_MENU_PERMISSION_URL.replace("ACCESS_TOKEN", accessToken);
            RequestBody requestBody = RequestBody.create(
                    MediaType.parse("application/json; charset=utf-8"),
                    permission.toJSONString());
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();
            log.info(request.toString());
            Response response = client.newCall(request).execute();
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            log.info("修改公众号菜单栏返回结果【{}】", jsonObject);
            return jsonObject.getIntValue("errcode") == 0;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("设置菜单权限异常");
            return false;
        }
    }

    private Token getTokenFromWx(String appId, String appSecret){
        //为空从缓存取token,否则调用微信接口获取
        Token token = null;
        if(StringUtils.isBlank(appSecret)){
            String accessToken = thirdPartyWeChatService.getAccessToken(appId);
            if (org.apache.commons.lang3.StringUtils.isNotBlank(accessToken)) {
                token = new Token();
                token.setAccessToken(accessToken);
                token.setExpiresIn(7200);
            }
        }else {
            try {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(ACCESS_TOKEN_URL.replace("APPID", appId).replace("APP_SECRET", appSecret))
                        .get()
                        .build();
                Response response = client.newCall(request).execute();
                JSONObject jsonObject = JSONObject.parseObject(response.body().string());
                String accessToken = jsonObject.getString("access_token");
                String expiresIn = jsonObject.getString("expires_in");
                if(StringUtils.isNotEmpty(accessToken)){
                    token = new Token();
                    token.setAccessToken(accessToken);
                    token.setExpiresIn(Integer.parseInt(expiresIn));
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return token;
    }

    private String getAccessToken(String appId, String appSecret) {
        String redisKey = RedisKeyPrefixConstant.ACCESS_TOKEN+ appId;
        Object objectKey = redisTemplate.opsForValue().get(redisKey);
        String accessToken = "";
        if(Objects.nonNull(objectKey)){
            accessToken = objectKey.toString();
        }
        if (StringUtils.isBlank(accessToken)) {
                Token token = getTokenFromWx(appId, appSecret);
                if (token == null || StringUtils.isBlank(token.getAccessToken())) {
                    return null;
                }
                redisTemplate.opsForValue().set(redisKey, token.getAccessToken(), 6000, TimeUnit.SECONDS);
                accessToken = token.getAccessToken();
            }


      return accessToken;
    }

    private static JSONObject getMenuPermission(String accessToken) {
        try {
            OkHttpClient client = new OkHttpClient();
            String url = GET_MENU_PERMISSION_URL.replace("ACCESS_TOKEN", accessToken);
            Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .build();
            Response response = client.newCall(request).execute();
            return JSONObject.parseObject(response.body().string());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    @Override
    public AjaxResult getGzhStatus(String enterpriseId) {
        Enterprise enterprise = enterpriseService.selectEnterpriseById(Long.valueOf(enterpriseId));
        if (Objects.isNull(enterprise)) {
            throw new CustomException("油企不存在");
        }
        String gzhAppId = enterprise.getGzhAppId();
        String gzhAppSecret = enterprise.getGzhAppSecret();

        if (StringUtils.isBlank(gzhAppId) || StringUtils.isBlank(gzhAppSecret)) {
            throw new CustomException("请配置appId和appSecret");
        }


//
//        //获取token
//        String accessToken = getAccessToken(gzhAppId, gzhAppSecret);
//        if(StringUtils.isEmpty(accessToken)){
//            throw new CustomException("获取access_token失败!");
//        }

        boolean b = checkAuthorization(gzhAppId, gzhAppSecret);


        return null;
    }

    private static Map<String,String> buildUpdateColorRequestBody(String param, String card_id) {
        JSONObject requestBodyJson = new JSONObject();
        JSONObject cardJson = new JSONObject();
        JSONObject baseInfoJson = new JSONObject();

        MemberCardInfo memberCardInfo = extractValues(param);

        String backgroundPicUrl = null;
        ObjectMapper mapper = new ObjectMapper();
        try {
            JsonNode rootNode = mapper.readTree(param);

            JsonNode memberCardNode = rootNode.get("member_card");
            if (memberCardNode != null) {
                backgroundPicUrl = memberCardNode.get("background_pic_url").asText();
            }
        }catch (Exception e){
            log.info("buildUpdateColorRequestBody.backgroundPicUrl:[{}]",e.getMessage());
        }
        try {

            baseInfoJson.put("color", WxColorEnum.getValueByText(memberCardInfo.getColor()));
            baseInfoJson.put("logo_url", memberCardInfo.getLogoUrl());
            baseInfoJson.put("center_title", memberCardInfo.getCenterTitle());
            baseInfoJson.put("center_url", memberCardInfo.getCenterUrl());
            baseInfoJson.put("custom_url_name", memberCardInfo.getCustomUrlName());
            baseInfoJson.put("custom_url", memberCardInfo.getCustomUrl());
            baseInfoJson.put("promotion_url_name", memberCardInfo.getPromotionUrlName());
            baseInfoJson.put("promotion_url", memberCardInfo.getPromotionUrl());
            baseInfoJson.put("custom_url_sub_title", memberCardInfo.getCustomUrlSubTitle());
            baseInfoJson.put("promotion_url_sub_title", memberCardInfo.getPromotionUrlSubTitle());
            baseInfoJson.put("center_sub_title", memberCardInfo.getCenterSubTitle());
            baseInfoJson.put("title", memberCardInfo.getTitle());

            cardJson.put("base_info", baseInfoJson);
            cardJson.put("background_pic_url",backgroundPicUrl);

            requestBodyJson.put("card_id", card_id);
            requestBodyJson.put("member_card", cardJson);
        } catch (JSONException e) {
            log.info("buildUpdateColorRequestBody.requestBodyJson:[{}]",e.getMessage());
        }
        Map<String,String> hashMap = new HashMap<>();
        hashMap.put("res",requestBodyJson.toString());
        hashMap.put("logoUrl",memberCardInfo.getLogoUrl());
        return hashMap;
    }

    @Override
    public AjaxResult getGzhMenu(Long enterpriseId) throws Exception {
        Enterprise enterprise = enterpriseService.selectEnterpriseById(enterpriseId);
        if (Objects.isNull(enterprise)) {
            throw new CustomException("油企不存在");
        }
        String gzhAppId = enterprise.getGzhAppId();
        String gzhAppSecret = enterprise.getGzhAppSecret();
        String accessToken = getAccessToken(gzhAppId, gzhAppSecret);

        JSONObject menuPermission = getMenuPermission(accessToken);

        String result = replaceImageValues(menuPermission.toString(),accessToken);
        return AjaxResult.success( JSONObject.parseObject(result));
    }

    public static String transformJson(String json) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(json);

        if (rootNode.has("button")) {
            JsonNode buttonArrayNode = rootNode.get("button");

            for (JsonNode buttonNode : buttonArrayNode) {
                if (buttonNode.has("sub_button")) {
                    JsonNode subButtonNode = buttonNode.get("sub_button").get("list");
                    ((ObjectNode) buttonNode).set("sub_button", subButtonNode);
                }
            }
        }

        return mapper.writeValueAsString(rootNode);
    }



    @Override
    public AjaxResult getLinkedMiniProgram(Long enterpriseId) {
        Enterprise enterprise = enterpriseService.selectEnterpriseById(enterpriseId);
        if (Objects.isNull(enterprise)) {
            throw new CustomException("油企不存在");
        }
        String gzhAppId = enterprise.getGzhAppId();
        String gzhAppSecret = enterprise.getGzhAppSecret();
        String accessToken = getComponentAccessToken();
        String associatedMiniPrograms = getAssociatedMiniPrograms(accessToken, gzhAppId);


        return null;
    }

    @Override
    public AjaxResult updateCardInfo(Long enterpriseId, String param) {
        Enterprise enterprise = enterpriseService.selectEnterpriseById(Long.valueOf(enterpriseId));
        if (Objects.isNull(enterprise)) {
            throw new CustomException("油企不存在");
        }
        String gzhAppId = enterprise.getGzhAppId();
        String gzhAppSecret = enterprise.getGzhAppSecret();


        String cardId = enterprise.getCardId();
        if (StringUtils.isEmpty(cardId)) {
            throw new CustomException("未开通会员卡");
        }

        OkHttpClient client = new OkHttpClient();

        String accessToken = getAccessToken(gzhAppId, gzhAppSecret);

        try {

            String cardIdRequestBody = "{\"card_id\": \"" + cardId + "\"}";
            RequestBody cardContentBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), cardIdRequestBody);
            Request cardContentRequest = new Request.Builder()
                    .url(CARD_GET_URL.replace("ACCESS_TOKEN", accessToken))
                    .post(cardContentBody)
                    .build();

            Response cardContentResponse = client.newCall(cardContentRequest).execute();
            String cardContentResponseBody = cardContentResponse.body().string();
            log.info("当前会员卡信息【{}】",cardContentResponseBody);


            //修改
            Map<String,String> hashMap = buildUpdateColorRequestBody(param, cardId);
            String res = hashMap.get("res");
            log.info("修改会员卡信息参数【{}】",res);
            RequestBody body1 = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), res);
            Request updateColorRequest = new Request.Builder()
                    .url(CARD_UPDATE_URL.replace("ACCESS_TOKEN", accessToken))
                    .post(body1)
                    .build();
            Response updateColorResponse = client.newCall(updateColorRequest).execute();
            String updateColorResponseBody = updateColorResponse.body().string();
            JSONObject jsonObject = JSONObject.parseObject(updateColorResponseBody);
            log.info("修改公众号菜单栏返回结果【{}】", jsonObject);
            if(  jsonObject.getIntValue("errcode") == 0){
                // 修改油企会员卡头像
                Enterprise enterpriseCardLogo = new Enterprise();
                enterpriseCardLogo.setEnterpriseId(enterprise.getEnterpriseId());
                String logoUrl = hashMap.get("logoUrl");
                enterpriseCardLogo.setCardLogo(logoUrl);
                enterpriseService.updateEnterpriseCardLogo(enterpriseCardLogo);
                return AjaxResult.success("修改会员卡成功");
            }
            log.info(updateColorResponseBody);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("修改失败");
        }
        return AjaxResult.error("修改失败");
    }

    @Override
    public AjaxResult getCardInfo(Long enterpriseId) {
        Enterprise enterprise = enterpriseService.selectEnterpriseById(Long.valueOf(enterpriseId));
        if (Objects.isNull(enterprise)) {
            throw new CustomException("油企不存在");
        }
        String gzhAppId = enterprise.getGzhAppId();
        String gzhAppSecret = enterprise.getGzhAppSecret();


        String cardId = enterprise.getCardId();
        if (StringUtils.isEmpty(cardId)) {
            throw new CustomException("未开通会员卡");
        }

        OkHttpClient client = new OkHttpClient();

        String accessToken = getAccessToken(gzhAppId, gzhAppSecret);

        try {

            String cardIdRequestBody = "{\"card_id\": \"" + cardId + "\"}";
            RequestBody cardContentBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), cardIdRequestBody);
            Request cardContentRequest = new Request.Builder()
                    .url(CARD_GET_URL.replace("ACCESS_TOKEN", accessToken))
                    .post(cardContentBody)
                    .build();

            Response cardContentResponse = client.newCall(cardContentRequest).execute();
            String cardContentResponseBody = cardContentResponse.body().string();
            Map<String,Object> hashMap = new HashMap<>();
            hashMap.put("response",JSONObject.parseObject(cardContentResponseBody));
            hashMap.put("backgroundPicUrl",enterprise.getBackgroundPicUrl());
            log.info("当前会员卡信息【{}】",cardContentResponseBody);
            return AjaxResult.success("查询成功",hashMap);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    public  String getComponentAccessToken() {
        if ( !redisTemplate.hasKey("third_party:component_access_token") || Objects.isNull(redisTemplate.opsForValue().get("third_party:component_access_token").toString())){
            HashMap<String, Object> paramsHashMap = new HashMap<>();
            paramsHashMap.put("component_appid",componentAppId);
            paramsHashMap.put("component_appsecret",componentAppSecret);
            paramsHashMap.put("component_verify_ticket",redisTemplate.opsForValue().get("third_party:cloud_component_verify_ticket").toString());

            /** 发送Https请求到微信 */

            try {
                net.sf.json.JSONObject resultJson= HttpUtils.doPostJson(
                        "https://api.weixin.qq.com/cgi-bin/component/api_component_token", JSON.toJSONString(paramsHashMap));
                redisTemplate.opsForValue().set("third_party:component_access_token", resultJson.get("component_access_token").toString(),110, TimeUnit.MINUTES);
            } catch (Exception e) {
                log.info(e.toString());
            }
        }
        return redisTemplate.opsForValue().get("third_party:component_access_token").toString();

    }

    private String getAssociatedMiniPrograms(String accessToken, String appId) {


        String requestBody = "{\"appid\": \"" + appId + "\"}";

        RequestBody body = RequestBody.create(MediaType.parse("application/json"), requestBody);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(WXAMP_LINK_GET.replace("ACCESS_TOKEN", accessToken))
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                return response.body().string();
            } else {
                log.info("查询关联小程序异常");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    private String replaceImageValues(String menuInfoResponse, String accesToken) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(menuInfoResponse);

            JsonNode buttonNode = rootNode.path("selfmenu_info").path("button");
            replaceImageValuesInNode(buttonNode, accesToken);

            return objectMapper.writeValueAsString(rootNode);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static MemberCardInfo extractValues(String json) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode rootNode = mapper.readTree(json);

            JsonNode memberCardNode = rootNode.get("member_card");
            if (memberCardNode != null) {
                JsonNode baseInfoNode = memberCardNode.get("base_info");
                if (baseInfoNode != null) {
                    String centerUrl = Objects.nonNull(baseInfoNode.get("center_url")) ? baseInfoNode.get("center_url").asText() : null;
                    String color = Objects.nonNull(baseInfoNode.get("color")) ? baseInfoNode.get("color").asText() : null;
                    String logoUrl = Objects.nonNull(baseInfoNode.get("logo_url")) ? baseInfoNode.get("logo_url").asText() : null;
                    String description = Objects.nonNull(baseInfoNode.get("description")) ? baseInfoNode.get("description").asText() : null;
                    String customUrl = Objects.nonNull(baseInfoNode.get("custom_url")) ? baseInfoNode.get("custom_url").asText() : null;
                    String centerSubTitle = Objects.nonNull(baseInfoNode.get("center_sub_title")) ? baseInfoNode.get("center_sub_title").asText() : null;
                    String centerTitle = Objects.nonNull(baseInfoNode.get("center_title")) ? baseInfoNode.get("center_title").asText() : null;
                    String customUrlName = Objects.nonNull(baseInfoNode.get("custom_url_name")) ? baseInfoNode.get("custom_url_name").asText() : null;
                    String promotionUrlName = Objects.nonNull(baseInfoNode.get("promotion_url_name")) ? baseInfoNode.get("promotion_url_name").asText() : null;
                    String promotionUrl = Objects.nonNull(baseInfoNode.get("promotion_url")) ? baseInfoNode.get("promotion_url").asText() : null;
                    String customUrlSubTitle = Objects.nonNull(baseInfoNode.get("custom_url_sub_title")) ? baseInfoNode.get("custom_url_sub_title").asText() : null;
                    String promotionUrlSubTitle = Objects.nonNull(baseInfoNode.get("promotion_url_sub_title")) ? baseInfoNode.get("promotion_url_sub_title").asText() : null;
                    String title = Objects.nonNull(baseInfoNode.get("title")) ? baseInfoNode.get("title").asText() : null;

                    return MemberCardInfo.builder()
                            .centerUrl(centerUrl)
                            .color(color)
                            .logoUrl(logoUrl)
                            .description(description)
                            .customUrl(customUrl)
                            .centerSubTitle(centerSubTitle)
                            .centerTitle(centerTitle)
                            .customUrlName(customUrlName)
                            .promotionUrlName(promotionUrlName)
                            .promotionUrl(promotionUrl)
                            .customUrlSubTitle(customUrlSubTitle)
                            .promotionUrlSubTitle(promotionUrlSubTitle)
                            .title(title)
                            .build();

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String uploadImgToWx(Long enterpriseId, String imgUrl) {
        Enterprise enterprise = enterpriseService.selectEnterpriseById(enterpriseId);
        if (Objects.isNull(enterprise)) {
            throw new CustomException("油企不存在");
        }
        String gzhAppId = enterprise.getGzhAppId();
        String gzhAppSecret = enterprise.getGzhAppSecret();
        String accessToken = getAccessToken(gzhAppId, gzhAppSecret);


        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(imgUrl)
                .get()
                .build();
        //获取图片
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                byte[] mediaData = response.body().bytes();
                RequestBody requestBody = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("media", "file.jpg",
                                RequestBody.create(MediaType.parse("image/jpeg"), mediaData))
                        .build();

                Request uploadRequest = new Request.Builder()
                        .url(MEDIA_UPLOAD_URL.replace("ACCESS_TOKEN", accessToken))
                        .post(requestBody)
                        .build();

                try (Response uploadResponse = client.newCall(uploadRequest).execute()) {
                    if (uploadResponse.isSuccessful()) {
                        String responseBody = uploadResponse.body().string();
                        //{"media_id":"IQ1SHO3_wxxYhZ1ghPcrzYV_FgtQASWmZw8x5UrptetG4h9s6Xxz5K1e0G9aHTIS",
                        // "url":"http:\/\/mmbiz.qpic.cn\/sz_mmbiz_png\/xOt6vPRQej9ibicA8icQe3uRcWO6xFEkmkic9x40Dbb1Rmqqib6May5OMBwRQUcbsoD2PibMWxSeNuiaeEDpBzdia2jaeA\/0?wx_fmt=png","item":[]}
                        log.info("上传图片到微信，返回结果：[{}]",responseBody);
//                        String mediaId = com.google.gson.JsonParser.parseString(responseBody)
//                                .getAsJsonObject().get("media_id").getAsString();
                        return responseBody;
                    } else {
                        log.error("上传图片失败: " + uploadResponse.code());
                    }
                }
            } else {
               log.error("上传图片失败 " + response.code());
            }
        }catch (IOException e){
            log.error("上传出现异常", e);
        }

        return "";
    }

    private String getPicUrl(String accessToken, String mediaId){
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(GET_MEDIA_URL.replace("access_token", accessToken)+ mediaId)
                .build();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                ResponseBody responseBody = response.body();
                if (responseBody != null) {
                    InputStream inputStream = responseBody.byteStream();
//                    saveImageToFile(inputStream, savePath);
//                    System.out.println("图片保存成功: " + savePath);
                }
            } else {
                log.error("HTTP请求失败，错误码：" + response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
            return null;
    }

    private void replaceImageValuesInNode(JsonNode node, String accessToken) {
        if (node.isArray()) {
            for (JsonNode itemNode : node) {
                replaceImageValuesInNode(itemNode,accessToken);

            }
        } else {
            String type = node.path("type").asText();
            if (type.equals("media_id")) {
                String mediaId = node.path("media_id").asText();
                String imageUrl = getImageUrl(mediaId,accessToken);
                ((ObjectNode) node).put("value", imageUrl);
            }

            //修改时前端传过来的Key其实是需要展示的内容，根据通过微信接口查到的key去数据库获取
            if(type.equals("click")){
                String value = wxMenuMapper.getMenuByMenuKey(node.path("key").asText());
                ((ObjectNode) node).put("key", value);
            }


            JsonNode subButtonNode = node.path("sub_button").path("list");
            if (!subButtonNode.isMissingNode()) {
                replaceImageValuesInNode(subButtonNode,accessToken);
            }
        }
    }

    private static String getImageUrl(String mediaId,String accessToken) {
       String imageUrl = "";

        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\"media_id\":\"" + mediaId + "\"}");
        Request request = new Request.Builder()
                .url(GET_MATERIAL_URL.replace("ACCESS_TOKEN",accessToken))
                .post(body)
                .build();
        OkHttpClient client = new OkHttpClient();
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                byte[] imageBytes = response.body().bytes();

                // 将图片数据转换为 Base64 编码
                String base64Image = Base64.getEncoder().encodeToString(imageBytes);
                return "data:image/jpeg;base64," + base64Image;
            } else {
                log.info("获取图片失败. Response Code: " + response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return imageUrl;
    }



    private boolean checkAuthorization(String appId, String appSecret) {
        // 获取第三方平台的访问令牌
        String componentAccessToken = getComponentAccessToken();
//        String componentAccessToken = getAccessToken(componentAppId, componentAppId);
        if (StringUtils.isNotEmpty(componentAccessToken)) {
            // 构造请求参数
            String requestBody = "{\"component_appid\":\"" + componentAppId + "\",\"authorizer_appid\":\"" + appId + "\"}";

            OkHttpClient client = new OkHttpClient();

            Request request = new Request.Builder()
                    .url(GET_GZH_AUTHORIZER_INFO_URL.replace("ACCESS_TOKEN", componentAccessToken))
                    .post(RequestBody.create(MediaType.parse("application/json"), requestBody))
                    .build();

            try {
                // 发送请求，获取响应
                Response response = client.newCall(request).execute();

                // 判断响应状态码
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();

                    // 解析响应，判断是否已授权
                    // 进行相应的处理
                    // ...
                    return true;
                } else {
                    log.error("请求失败，状态码：" + response.code());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return false;
    }


    @Override
    public String getGzhToken(Long enterpriseId) {
        Enterprise enterprise = enterpriseService.selectEnterpriseById(enterpriseId);
        if (Objects.isNull(enterprise)) {
            throw new CustomException("油企不存在");
        }
        String gzhAppId = enterprise.getGzhAppId();
        String gzhAppSecret = enterprise.getGzhAppSecret();
        String accessToken = getAccessToken(gzhAppId, gzhAppSecret);
        if (StringUtils.isEmpty(accessToken)) {
            throw new CustomException("获取access_token失败!");
        }
        return accessToken;
    }


}
